;
(function() {
	var KAMap = function(options) {
		this.geolocation = null;
		this.mapObj = null;
		this.windowsArr = [];
		this.marker = [];
		this.markers = [];
		this._lat = null;
		this._lng = null;
		this.render = options.render || '';
		this.toolBar = null;
		this.mapZoomLevel = 15;
		this.district = null;
	};
	KAMap.prototype = {
		mapInit: function(center,callback) {
			var _that = this;
			this.mapObj = new AMap.Map(this.render, {
				level: this.mapZoomLevel
			});
			this.mapObj.plugin(["AMap.ToolBar"], function() {
				_that.toolBar = new AMap.ToolBar();
				_that.mapObj.addControl(this.toolBar);
			});
			this.mapObj.plugin('AMap.Geolocation', function() {
				_that.geoInit(false);
			});
			AMap.event.addListener(this.mapObj, 'dragstart', function(e) { //移动地图后再定位时不设为地图中心点
				_that.geoRemove();
				_that.geoInit(false);
				_that.setLocation();
			});
			AMap.service(["AMap.DistrictSearch"], function() {
				//实例化DistrictSearch
				_that.district = new AMap.DistrictSearch({
					subdistrict: 1, //返回下一级行政区
					extensions: 'all', //返回行政区边界坐标组等具体信息
					level: 'city' //查询行政级别为 市
				});
			});
			this.mapObj.setZoomAndCenter(this.mapZoomLevel, center);			
		},
		/**
		 * 设置地图中心点位置
		 * @param {Object} c 中心点位置 {lng:经度,lat:纬度,zoomlevel:缩放级别，默认值15}
		 */
		setCenter: function(c) {
			this.mapObj.setZoomAndCenter(c.zoomlevel || this.mapZoomLevel, new AMap.LngLat(c.lng, c.lat));
		},
		setLocation: function() {
			if (this.geolocation) {
				this.geolocation.watchPosition();
			} else {
				setTimeout(this.setLocation, 1000);
			}
		},
		geoInit: function(isCenter) {
			this.geolocation = new AMap.Geolocation({
				enableHighAccuracy: true, //是否使用高精度定位，默认:true  
				timeout: 100000, //超过10秒后停止定位，默认：无穷大  
				maximumAge: 0, //定位结果缓存0毫秒，默认：0  
				convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true  
				showButton: false, //显示定位按钮，默认：true  
				buttonPosition: 'LB', //定位按钮停靠位置，默认：'LB'，左下角  
				buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)  
				showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true  
				markerOptions: {
					title: "locationIMG",
					offset: {
						x: -10,
						y: 20
					},
					icon: new AMap.Icon({
						image: "http://webapi.amap.com/theme/v1.2/my_location.png",
						size: new AMap.Size(16, 16),
						imageOffset: {
							x: -24,
							y: -2
						}
					})
				},
				showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true  
				panToLocation: isCenter, //定位成功后将定位到的位置作为地图中心点，默认：true  
				zoomToAccuracy: true //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false  
			});
			this.mapObj.addControl(this.geolocation);
			this.geoSuccessListener = AMap.event.addListener(this.geolocation, 'complete', this.OnComplete); //返回定位信息,初始时定位后设为地图中心点  
			this.geoErrorListener = AMap.event.addListener(this.geolocation, 'error', this.onError); //返回定位出错信息  
		},
		geoRemove: function() {
			this.mapObj.removeControl(this.geolocation);
			AMap.event.removeListener(this.geoSuccessListener);
			AMap.event.removeListener(this.geoErrorListener);
			if ($("div[title='locationIMG']")) {
				$("div[title='locationIMG']").parent().remove();
			}
		},
		OnComplete: function(data) {
			/*
			var lng, lat;
			lng = data.position.getLng();
			lat = data.position.getLat(); 
			*/
			this._lng = data.position.getLng();
			this._lat = data.position.getLat();
			lnglatXY = new AMap.LngLat(data.position.getLng(), data.position.getLat());
			var nickName = $('#nickname').text();
			var imageURL = $('#mines').find('img').attr('src');
			this.geocoder();
			this.setMemberLocation(openId, data.position.getLng(), data.position.getLat(), imageURL, '1', 20, nickName);
		},
		geocoder: function() {
			var MGeocoder;
			//加载地理编码插件
			AMap.service(["AMap.Geocoder"], function() {
				MGeocoder = new AMap.Geocoder({
					radius: 1000,
					extensions: "all"
				});
				//逆地理编码
				MGeocoder.getAddress(lnglatXY, function(status, result) {
					if (status === 'complete' && result.info === 'OK') {
						geocoder_CallBack(result);
					}
				});
			});
		},
		/**
		 * 获取城市编码
		 * @param {Object} cityName
		 * @param {Object} callback
		 */
		getCityCode: function(cityName, callback) {
			//行政区查询
			this.district.setLevel('city'); //行政区级别		
			this.district.search(cityName, function(status, result) {
				if (result && result.info == 'OK') {
					var dis = result.districtList,
						isTrue = false;
					for (var i = 0, l = dis.length; i < l; i++) {
						if (dis[i].level == 'city') {
							callback(dis[i]);
							isTrue = true;
							break;
						}
					}
					isTrue ? '' : callback(dis[0]);
				}
			});
		},
		//获取团员地址时，如果某个人团员下线了，则把头像从地图上移除掉
		deleteNotInMarkers: function(memberData) {
			var flag = true;
			for (var i = 0, j = this.markers.length; i < j; i++) {
				var m = this.markers[i];
				flag = true;
				for (var _i = 0, _j = memberData.length; _i < _j; _i++) {
					var md = memberData[_i];
					if (m.getTitle() === md.OpenID) {
						flag = false;
						break;
					}
				}
				if (flag) {
					m.setMap(null);
				}
			}
		},
		//回调函数

		geocoder_CallBack: function(data) {
			//返回地址描述
			destinationName = data.regeocode.formattedAddress;
		},

		getExistsInMarkers: function(titleOpenID) {
			for (var i = 0; i < markers.length; i++) {
				var m = markers[i];
				if (m.getTitle() === titleOpenID) {
					return m;
				}
			}
			return null;
		},

		setMemberLocation: function(_oID, _lng, _lat, _imageUrl, _isLeader, currentMember, nickNameIn) {
			if (!_imageUrl || _imageUrl == '') {
				return;
			}
			var _m = getExistsInMarkers(_oID);
			if (_m) {
				if (currentMember > 1) {
					_m.setzIndex(currentMember);
				}
				_m.setMap(mapObj);
				_m.setPosition(new AMap.LngLat(_lng, _lat));
			} else {
				var marker = new AMap.Marker({});
				//自定义点标记内容     
				var markerContent = document.createElement("div");
				markerContent.className = "user_popup";
				//头像
				var markerContentDiv2 = document.createElement("div");
				markerContentDiv2.className = "user_img_blue";
				var markerP2 = document.createElement("p");
				var markerImg2 = document.createElement("img");
				markerImg2.src = _imageUrl !== null && _imageUrl !== "" ? _imageUrl : "/Content/images/CO_02_Icon05_Norm.png";
				markerImg2.width = 50;
				markerImg2.height = 50;
				markerP2.appendChild(markerImg2);
				markerContentDiv2.appendChild(markerP2);
				var markerP22 = document.createElement("p");
				markerP22.className = "user_popup_name";
				markerP22.innerHTML = nickNameIn;
				markerContentDiv2.appendChild(markerP22);
				markerContent.appendChild(markerContentDiv2);
				var markerContentDiv3 = document.createElement("div");
				markerContentDiv3.className = "downarrow";
				var markerImg3 = document.createElement("img");
				markerImg3.src = "img/arrow_popup_blue.png";
				markerContentDiv3.appendChild(markerImg3);
				markerContent.appendChild(markerContentDiv3);
				if (currentMember > 1) {
					marker.setzIndex(currentMember);
				}
				marker.setTitle(_oID)
				marker.setContent(markerContent); //更新点标记内容
				marker.setPosition(new AMap.LngLat(_lng, _lat)); //更新点标记位置                    
				marker.setMap(mapObj);
				mapObj.setZoomAndCenter(14, new AMap.LngLat(_lng, _lat));
				mapObj.setFitView();
				markers.push(marker);
			}
		},
		/**
		 * 输入提示
		 * @param {Object} keywords 查询关键字
		 * @param {Object} cityName 城市名称
		 * @param {Object} callback 回调函数
		 */
		autoSearch: function(keywords, cityName, callback) {
			if (keywords && cityName) {
				var auto;
				//加载输入提示插件
				AMap.service(["AMap.Autocomplete"], function() {
					auto = new AMap.Autocomplete({
						city: cityName //城市，默认全国
					});
					auto.search(keywords,
						/*function(status, result) {
													autocomplete_CallBack(result);
												}*/
						callback);
				});
			} else {
				return false;
			}
		},
		//定位选择输入提示关键字

		focus_callback: function() {
			if (navigator.userAgent.indexOf("MSIE") > 0) {
				document.getElementById("keyword").onpropertychange = autoSearch;
			}
		},

		//鼠标滑过查询结果改变背景样式，根据id打开信息窗体

		openMarkerTipById1: function(pointid, thiss) {
			this.style.background = '#CAE1FF';
			windowsArr[pointid].open(mapObj, marker[pointid]);
		},
		//添加查询结果的marker&infowindow   

		addmarker: function(i, d) {
			var _that = this;
			var lngX = d.location.lng || d.location.getLng();
			var latY = d.location.lat || d.location.getLat();
			var mar = new AMap.Marker({
				map: this.mapObj,
				icon: "http://webapi.amap.com/images/" + (i + 1) + ".png",
				position: new AMap.LngLat(lngX, latY)
			});
			this.marker.push(new AMap.LngLat(lngX, latY));
			var infoWindow = new AMap.InfoWindow({
				content: "<h3><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></h3>" + this.tipContents(d.type, d.address, d.tel),
				size: new AMap.Size(300, 0),
				autoMove: true,
				offset: new AMap.Pixel(0, -30)
			});
			this.windowsArr.push(infoWindow);
			AMap.event.addListener(mar, "click", function(e) {
				infoWindow.open(_that.mapObj, mar.getPosition());
			});
		},
		//infowindow显示内容

		tipContents: function(type, address, tel) { //窗体内容
			if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
				type = "暂无";
			}
			if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
				address = "暂无";
			}
			if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
				tel = "暂无";
			}
			var str = "  地址：" + address + "<br />  电话：" + tel + " <br />  类型：" + type;
			return str;
		},
		//基本地图加载
		placeSearch: function(keyword, city, callback) {
			var MSearch;
			AMap.service(["AMap.PlaceSearch"], function() {
				MSearch = new AMap.PlaceSearch({ //构造地点查询类
					pageSize: 15,
					pageIndex: 1,
					city: city //城市
				});
				//关键字查询
				MSearch.search(keyword,
					/*function(status, result){
							        	if(status === 'complete' && result.info === 'OK'){
							        		keywordSearch_CallBack(result);
							        	}
							        }*/
					callback);
			});
		}

	};
	//需要注意赋值的位置问题
	/*window.KAMap = function(options) {
		return new KAMap(options);
	}();*/
	window.KAMap = KAMap;
})(window);